/**
 * 
 */
package com.cn.customer.housekeeping.housekeepingc.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import com.cn.customer.housekeeping.housekeepingc.bean.BaseResp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class Utils {


	private static SimpleDateFormat sdf = null;
	public  static String formatUTC(long l, String strPattern) {
		if (TextUtils.isEmpty(strPattern)) {
			strPattern = "yyyy-MM-dd HH:mm:ss";
		}
		if (sdf == null) {
			try {
				sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
			} catch (Throwable e) {
			}
		} else {
			sdf.applyPattern(strPattern);
		}
		return sdf == null ? "NULL" : sdf.format(l);
	}

	/**
	 * 检测是否说有的权限都已经授权
	 * @param grantResults
	 * @return
	 * @since 2.5.0
	 *
	 */
	public static boolean verifyPermissions(int[] grantResults) {
		for (int result : grantResults) {
			if (result != PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}
	/**
	 *
	 * @since 2.5.0
	 *
	 */
	public static boolean checkPermissions(Activity context , String... permissions) {
		List<String> needRequestPermissonList = findDeniedPermissions(context,permissions);
		if (null != needRequestPermissonList
				&& needRequestPermissonList.size() > 0) {
			ActivityCompat.requestPermissions(context,
					needRequestPermissonList.toArray(
							new String[needRequestPermissonList.size()]),
					PERMISSON_REQUESTCODE);
			return false;
		}else{
			return true;
		}

	}

	/**
	 * 获取权限集中需要申请权限的列表
	 *
	 * @param permissions
	 * @return
	 * @since 2.5.0
	 *
	 */
	public static List<String> findDeniedPermissions(Activity context, String[] permissions) {
		List<String> needRequestPermissonList = new ArrayList<String>();
		for (String perm : permissions) {
			if (ContextCompat.checkSelfPermission(context,
					perm) != PackageManager.PERMISSION_GRANTED
					|| ActivityCompat.shouldShowRequestPermissionRationale(
					context, perm)) {
				needRequestPermissonList.add(perm);
			}
		}
		return needRequestPermissonList;
	}
	public static final int PERMISSON_REQUESTCODE = 0;
	/**
	 * 验证手机号码是否合乎规则
	 */
	public  static boolean validatePhoneNumber(String phoneNumbers, Context context) {
		String phoneNumber = phoneNumbers.replace(" ", "");
		if (!NetworkUtil.isNetworkAvailable(context)) {
			ToastUtil.makeText(context, "您的网络异常,请检查网络后重新尝试");
			return false;
		}
		if (!StringUtil.isMobileNO(phoneNumber)) {
			ToastUtil.makeText(context, "请输入正确的手机号码");
			return false;
		}
		return true;
	}


	/**
	 * 验证手机号\动态验证码
	 */
	public static boolean validateCode(String phoneNumbers, String validateCode,Context context) {
		String phoneNumber = phoneNumbers.replace(" ", "");
		if (!NetworkUtil.isNetworkAvailable(context)) {
			ToastUtil.makeText(context, "您的网络异常,请检查网络后重新尝试");
			return false;
		}
		if (!validatePhoneNumber(phoneNumber,context))
			return false;

//        if (!isVerifyCodeRight(validateCode)) {
//            ToastUtil.makeText(this, "验证码错误，请重新输入");
//            return false;
//        }

		return true;
	}

	/**
	 * @return
	 * @Description 判断是否为6位验证码
	 */

	public static boolean isVerifyCodeRight(String validateCode) {
		return validateCode.matches("\\d{4}");
	}

	/**
	 * 密码的正确性
	 */
	public static boolean validate(String password,Context context) {
		if (!NetworkUtil.isNetworkAvailable(context)) {
			ToastUtil.makeText(context, "您的网络异常,请检查网络后重新尝试");
			return false;
		}
		if (password.length() < 6 || password.length() > 20) {
			ToastUtil.makeText(context, "您的密码输入错误，请重新输入");
			return false;
		}

		return true;
	}

	/**
	 * 获取商户订单号
	 *
	 */
	public static  String getIndent(String merchNo){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String date = sdf.format(new Date());
		String orderno=merchNo+date+Math.round((9999999*Math.random()));
		return  orderno;
	}
	  UtilsListener uitls;
	public void   setListener(UtilsListener listens){
		this.uitls=listens;
	}
	public static void bequit(BaseResp s, Activity activity){
		if (s!=null){
			if (s.getCode()==100003){
				ToastUtil.makeText(activity,"token过期,请重新登录");
				quit(activity);
			}else {
				ToastUtil.makeText(activity, s.getMessage());
			}
		}
	}
	public  void bequits(BaseResp s,Activity activity){
		if (s!=null){
			if (s.getCode()==100003){
				outToken();
			}else {
				ToastUtil.makeText(activity, s.getMessage());
			}
		}
	}
	 Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what){
				case 1:
					uitls.UitlListener();
					break;
			}
		}
	};
	public  void outToken(){
		handler.sendEmptyMessage(1);
//		OkHttpManager httpManager = BridgeFactory.getBridge(Bridges.HTTP);
//		httpManager.requestAsyncPostByTag(URLUtil.url_join_group, "Utils", new ITRequestResult<BaseResp>() {
//					@Override
//					public void onCompleted() {
//
//					}
//
//					@Override
//					public void onSuccessful(BaseResp entity) {
//						handler.sendEmptyMessage(1);
//					}
//
//					@Override
//					public void onFailure(BaseResp entity) {
//					}
//
//				}, BaseResp.class, new Param("group_uid", ""), new Param("group_id", "")
//		);
	}
	public static void quit(Activity activity){
//		EBSharedPrefManager manager = BridgeFactory.getBridge(Bridges.SHARED_PREFERENCE);
//		String phone = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.phone, "");
//		String headpic = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.headpic, "");
//		manager.getKDPreferenceUserInfo().clear();
//		manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.phone, phone);
//		manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.headpic, headpic);
//		BroadcastManager.getInstance(activity).sendBroadcast(SealConst.EXIT);
	}
	public  static String[] getVersionInfo(Activity activity) {
		String[] version = new String[2];

		PackageManager packageManager = activity.getPackageManager();

		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(activity.getPackageName(), 0);
			version[0] = String.valueOf(packageInfo.versionCode);
			version[1] = packageInfo.versionName;
			return version;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}

		return version;
	}
	public interface  UtilsListener{
		void UitlListener();
	}


	public static  String getChannel(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			ApplicationInfo appInfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			return appInfo.metaData.getString("UMENG_CHANNEL");
		} catch (PackageManager.NameNotFoundException ignored) {
		}
		return "";

	}
}

